package server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class SimpleConnector {

    private SimpleService simpleService;
    private int port;
    private ServerSocket serverSocket;
    private ThreadPoolExecutor threadPoolExecutor;

    public SimpleService getSimpleService() {
        return simpleService;
    }

    public void setSimpleService(SimpleService simpleService) {
        this.simpleService = simpleService;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void init() {
        /**
         *
         */
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        this.threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );


        try {
            serverSocket = new ServerSocket(port);
            System.out.println("=====>>>Minicat start on port：" + port);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void start() {
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            try {
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket,
                                                                         this.simpleService.getSimpleEngine());
                requestProcessor.start();
                threadPoolExecutor.execute(requestProcessor);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
